package com.alogic.validator.impl.pwd;

import com.alogic.load.CommonObject;
import com.alogic.load.Loader;
import com.alogic.validator.Validator;
import com.anysoft.util.*;
import org.w3c.dom.Element;

/**
 * 字典列表
 *
 * @version 1.6.13.25 [20201110 duanyy] <br>
 * - 修复validator的问题
 */
public class Dictionary extends Validator.Abstract{
    protected boolean exclude = true;
    protected Loader<CommonObject> loader = null;

    @Override
    public void configure(Properties p) {
        super.configure(p);
        exclude = PropertiesConstants.getBoolean(p,"exclude",exclude,true);
    }

    @Override
    public void configure(Element e, Properties p) {
        XmlElementProperties props = new XmlElementProperties(e,p);
        configure(props);
        try {
            Factory<Loader<CommonObject>> f = new Factory<Loader<CommonObject>>();
            loader = f.newInstance(e, p, "loader");
        }catch (Exception ex){
            LOG.error("Can not create loader:" + XmlTools.node2String(e));
        }
    }

    @Override
    public boolean check(String value, Properties ctx, boolean throwException) {
        boolean result = exclude?true:false;

        if (loader != null){
            CommonObject found = loader.load(value,true);
            result = exclude?found == null:found != null;
        }

        if (!result && throwException){
            throw new BaseException(getCode(ctx),getMessage(ctx));
        }
        return result;
    }

    @Override
    public boolean check(String value, Properties ctx, Listener listener) {
        boolean result = exclude?true:false;
        if (loader != null){
            CommonObject found = loader.load(value,true);
            result = exclude?found == null:found != null;
        }

        if (listener != null){
            listener.result(result,value,this,ctx);
        }
        return result;
    }
}
